package com.shujia.spark.mllib

import breeze.linalg.SparseVector
import org.apache.spark.ml.classification.LogisticRegressionModel
import org.apache.spark.ml.linalg
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.sql.{DataFrame, Row, SparkSession}

object Demo7UseImageModel {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .master("local[16]")
      .appName("point")
      .getOrCreate()
    import spark.implicits._
    import org.apache.spark.sql.functions._

    /**
     * 1、加载许哟识别的图片
     */
    val imageDF: DataFrame = spark
      .read
      .format("image")
      .load("C:\\Users\\shujia\\Desktop\\mllib\\test2")

    imageDF.printSchema()

    //取出图片路径和图片的数据
    val dataDF: DataFrame = imageDF.select($"image.origin" as "path", $"image.data" as "data")

    /**
     * 1、特征工程，将原始的图片的数据转换成向量
     */
    val featuresDF: DataFrame = dataDF.map {
      case Row(path: String, data: Array[Byte]) =>
        //处理数
        val xs: Array[Double] = data
          .map(byte => byte.toInt) //将二进制的数据转换成16进制
          //将白色的部分转换成1，将黑色部分转换成0
          .map((i: Int) => {
            if (i >= 0) {
              0.0
            } else {
              1.0
            }
          })
        //将特征转换成向量
        val features: linalg.SparseVector = Vectors.dense(xs).toSparse
        //取出图片名
        val name: String = path.split("/").last
        (name, features)
    }.toDF("name", "features")

    featuresDF.show(false)

    /**
     * 2、加载模型
     */
    val model: LogisticRegressionModel = LogisticRegressionModel.load("data/image_model")

    /**
     * 使用模型识别图片
     */
    val dataFrame: DataFrame = model.transform(featuresDF)


    dataFrame.show(100,false)
  }

}
